<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>创建学习笔记 - StudentHub</title>
    <link rel="shortcut icon" href="/public/favicon.ico" type="image/x-icon">
    <!-- 引入 Tailwind CSS -->
    <script src="https://cdn.tailwindcss.com"></script>
    <!-- 引入 Font Awesome -->
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
    <!-- 引入 jQuery -->
    <script src="/jquery-3.7.1.min.js"></script>
    <!-- 引入 wangEditor -->
    <script src="https://unpkg.com/wangeditor@4.7.15/dist/wangEditor.min.js"></script>

    <!-- 配置 Tailwind (Assuming the same config as home.html) -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF',
                        secondary: '#36D399',
                        neutral: {
                            100: '#F8FAFC',
                            200: '#E2E8F0',
                            300: '#CBD5E1',
                            400: '#94A3B8',
                            500: '#64748B',
                            600: '#475569',
                            700: '#334155',
                            800: '#1E293B',
                            900: '#0F172A',
                        }
                    },
                    fontFamily: {
                        inter: ['Inter', 'system-ui', 'sans-serif'],
                    },
                    boxShadow: {
                        'card': '0 10px 15px -3px rgba(0, 0, 0, 0.05), 0 4px 6px -2px rgba(0, 0, 0, 0.03)',
                        'card-hover': '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)',
                    }
                },
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .text-balance {
                text-wrap: balance;
            }
            .animate-fade-in {
                animation: fadeIn 0.5s ease-in-out;
            }
            .animate-slide-up {
                animation: slideUp 0.5s ease-out;
            }
            .scrollbar-hide {
                -ms-overflow-style: none;
                scrollbar-width: none;
            }
            .scrollbar-hide::-webkit-scrollbar {
                display: none;
            }
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        @keyframes slideUp {
            from { transform: translateY(20px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }
    </style>

</head>
<body class="font-inter bg-neutral-100 text-neutral-800">

    <!-- 导航栏 -->
<header class="sticky top-0 z-50 bg-white shadow-sm transition-all duration-300" id="navbar">
    <div class="container mx-auto px-4 py-3 flex items-center justify-between">
        <div class="flex items-center space-x-2">
            <a href="/qian/home.html" class="text-primary font-bold text-xl flex items-center">
                <i class="fa fa-graduation-cap mr-2"></i>
                <span>StudentHub</span>
            </a>
        </div>

        <nav class="hidden md:flex items-center space-x-6">
            <a href="/qian/home.html" class="text-primary font-medium">首页</a>
            <!-- 后台管理按钮 -->
            <a href="/hou/index.html" id="adminButton" class="hidden bg-primary text-white px-3 py-1 rounded font-medium hover:bg-primary/90 transition-colors">
                后台管理
            </a>
        </nav>

        <div class="flex items-center space-x-4">
            <!-- Logout Button -->
            <button id="logoutButton" class="text-red-500 hover:text-red-700 transition-colors font-medium hidden md:block">
                退出登录
            </button>

            <div class="relative hidden md:block">
                <label>
                    <input type="text" placeholder="搜索课程、学习资料..." class="pl-10 pr-4 py-2 rounded-full bg-neutral-100 focus:outline-none focus:ring-2 focus:ring-primary/30 transition-all w-48 focus:w-64">
                </label>
                <i class="fa fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-neutral-400"></i>
            </div>

            <div class="relative group">
                <a href="/qian/user-center.html" class="w-4 h-4 rounded-full overflow-hidden border-2 border-white hover:border-primary transition-all">
                    <!-- Server-side code should replace the src with the user's avatar from session -->
                    <img src="https://picsum.photos/id/64/200/200" alt="用户头像" class="w-full h-full object-cover rounded-full" style="width: 40px; height: 40px;">
                </a>

                <div class="absolute right-0 mt-2 w-48 bg-white rounded-lg shadow-lg py-2 z-10 opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-300 transform group-hover:translate-y-0 translate-y-2">
                    <a href="user.html" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                        <i class="fa fa-user-o mr-2"></i> 个人主页
                    </a>
                    <a href="#" class="block px-4 py-2 text-sm text-neutral-700 hover:bg-neutral-100">
                        <i class="fa fa-cog mr-2"></i> 设置
                    </a>
                    <div class="border-t border-neutral-200 my-1"></div>
                    <a href="#" class="block px-4 py-2 text-sm text-red-500 hover:bg-neutral-100">
                        <i class="fa fa-sign-out mr-2"></i> 退出登录
                    </a>
                </div>
            </div>

            <button class="md:hidden text-neutral-600 hover:text-primary transition-colors">
                <i class="fa fa-bars text-xl"></i>
            </button>
        </div>
    </div>
</header>

    <!-- 主内容区 -->
    <main class="container mx-auto px-4 py-8 md:py-12">
        <div class="bg-white rounded-xl shadow-lg p-6 w-full md:max-w-2xl mx-auto">
            <h1 class="text-xl md:text-2xl font-bold text-neutral-900 mb-6">创建学习笔记</h1>
            <form id="createArticleForm">
                <div class="mb-4">
                    <label for="articleTitle" class="block text-sm font-medium text-neutral-700 mb-1">标题</label>
                    <input type="text" id="articleTitle" name="articleTitle" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="请输入标题">
                </div>
                <div class="mb-4">
                    <label for="articleContent" class="block text-sm font-medium text-neutral-700 mb-1">内容</label>
                    <div id="editor" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" style="min-height: 300px;"></div>
                </div>
                <div class="mb-6">
                    <label for="articleCategory" class="block text-sm font-medium text-neutral-700 mb-1">类别</label>
                    <select id="articleCategory" name="articleCategory" class="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary">
                        <option value="">请选择类别</option>
                        <!-- Categories will be loaded here by JavaScript -->
                    </select>
                </div>
                <div class="flex justify-end space-x-3">
                    <button type="button" id="cancelButton" class="px-6 py-2 text-sm font-medium text-neutral-700 bg-gray-200 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-gray-500/30 transition-colors">取消</button>
                    <button type="submit" id="addButton" class="px-6 py-2 text-sm font-medium text-white bg-primary rounded-md hover:bg-primary/90 focus:outline-none focus:ring-2 focus:ring-primary/50 transition-colors">添加</button>
                </div>
            </form>
        </div>
    </main>

    <!-- 底部区域 -->
<footer class="bg-white border-t border-neutral-200 mt-12">
    <div class="container mx-auto px-4 py-8">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
            <div>
                <h3 class="text-lg font-bold text-neutral-900 mb-4">StudentHub</h3>
                <p class="text-neutral-600 text-sm mb-4">探索知识，提升能力，与优秀学子共同成长。</p>
                <div class="flex space-x-4">
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-github text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-twitter text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-linkedin text-xl"></i>
                    </a>
                    <a href="#" class="text-neutral-500 hover:text-primary transition-colors">
                        <i class="fa fa-weibo text-xl"></i>
                    </a>
                </div>
            </div>
        </div>

        <div class="border-t border-neutral-200 mt-8 pt-8 text-center text-neutral-500 text-sm">
            
        </div>
    </div>
</footer>

<script>
    $(document).ready(function() {
        // 检查 wangEditor 是否加载成功
        if (typeof window.wangEditor === 'undefined') {
            console.error('wangEditor 加载失败');
            alert('编辑器加载失败，请刷新页面重试');
            return;
        }

        try {
            // Initialize wangEditor
            const E = window.wangEditor;
            const editor = new E('#editor');
            
            // Configure editor
            editor.config.height = 300;
            editor.config.placeholder = '请输入内容';
            editor.config.zIndex = 1;
            
            // 配置图片上传
            editor.config.uploadImgServer = 'http://localhost:8082/api/upload/editorImage';
            editor.config.uploadFileName = 'editorImage';
            editor.config.uploadImgMaxSize = 5 * 1024 * 1024; // 5MB
            
            // 配置图片上传的回调函数
            editor.config.uploadImgHooks = {
                customInsert: function(insertImgFn, result) {
                    // result 即服务端的返回结果
                    if (result.errno === 0) {
                        // 从返回的数据中获取图片url
                        const url = result.data.url;
                        insertImgFn(url);
                    } else {
                        alert('图片上传失败：' + (result.message || '未知错误'));
                    }
                }
            };
            
            // 创建编辑器
            editor.create();

            // 添加错误处理
            editor.config.onerror = function (err) {
                console.error('编辑器错误:', err);
                alert('编辑器发生错误，请刷新页面重试');
            };

            // Dynamically set the header avatar from sessionStorage
            const userAvatarName = sessionStorage.getItem('avatarUrl'); // Get the avatar filename from sessionStorage using the key 'avatarUrl'
            const headerAvatar = $('#navbar a.rounded-full img'); // Corrected selector for the avatar image in the header
            const avatarBaseUrl = 'http://localhost:8082/upload/';
            if (userAvatarName && headerAvatar.length > 0) {
                headerAvatar.attr('src', avatarBaseUrl + userAvatarName);
            } else {
                // Optionally set a default avatar if not found in session
                headerAvatar.attr('src', 'http://localhost:8082/upload/default.jpg');
            }

            // Control visibility of Admin button based on user role
            const userRole = sessionStorage.getItem('userRole'); // Assuming user role is stored under this key
            const adminButton = $('#adminButton');

            if (userRole === 'ADMIN') {
                adminButton.removeClass('hidden');
            } else {
                adminButton.addClass('hidden');
            }

            // Handle Cancel button click
            $('#cancelButton').on('click', function() {
                window.history.back(); // Go back to the previous page
            });

            // Fetch categories
            function fetchCategoriesForDropdown() {
                $.ajax({
                    url: 'http://localhost:8082/api/tags/',
                    method: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        const categorySelect = $('#articleCategory');
                        categorySelect.empty(); // Clear existing options
                        categorySelect.append('<option value="">请选择类别</option>'); // Add default option

                        if (data.code === 200 && Array.isArray(data.data)) {
                            data.data.forEach(category => {
                                categorySelect.append(`<option value="${category.id}">${category.name}</option>`);
                            });
                        } else {
                            console.error('获取分类失败:', data.msg || '未知错误');
                            alert('获取类别数据失败');
                        }
                    },
                    error: function() {
                        console.error('分类请求失败');
                        alert('无法连接到类别接口');
                        const categorySelect = $('#articleCategory');
                        categorySelect.empty();
                        categorySelect.append('<option value="">加载分类失败</option>');
                    }
                });
            }

            // Handle form submission
            $('#createArticleForm').on('submit', function(event) {
                event.preventDefault(); // Prevent default form submission

                const title = $('#articleTitle').val();
                const content = editor.txt.html(); // Get HTML content from editor
                const tagId = $('#articleCategory').val(); // Get the selected category ID

                // Basic validation
                if (!title || !content || !tagId) {
                    alert('标题、内容和类别都不能为空！');
                    return;
                }

                // Get userId from sessionStorage - assuming it's available
                const userId = sessionStorage.getItem('userId');
                if (!userId) {
                     alert('用户未登录，请先登录！');
                     // Optionally redirect to login page
                     window.location.href = '/login.html'; // Or your login page path
                     return;
                }


                const articleData = {
                    title: title,
                    content: content,
                    tagId: parseInt(tagId), // Ensure tagId is a number
                    authorId: parseInt(userId) // Ensure userId is a number
                    // Add other fields if required by your backend API, e.g., author, status
                };
                console.log(articleData);
                

                $.ajax({
                    url: 'http://localhost:8082/api/articles/add',
                    type: 'POST',
                    contentType: 'application/json', // Specify content type as JSON
                    data: JSON.stringify(articleData), // Send data as JSON string
                    success: function(response) {
                        if (response.code === 200) {
                            alert('学习笔记创建成功！');
                            // Redirect to home page or the new article page
                            window.location.href = '/qian/home.html'; // Or redirect to the new article page if available
                        } else {
                            alert('创建学习笔记失败: ' + (response.msg || '未知错误'));
                        }
                    },
                    error: function(xhr, status, error) {
                        console.error('创建学习笔记请求失败:', error);
                        alert('创建学习笔记失败，请稍后重试。');
                    }
                });
            });

            // Initial fetch of categories when the page loads
            fetchCategoriesForDropdown();

            // Add logout functionality for the button
            $('#logoutButton').on('click', function(e) {
                e.preventDefault(); // Prevent default link behavior
                // Clear session storage
                sessionStorage.removeItem('userId');
                sessionStorage.removeItem('username'); // Assuming username is also stored
                sessionStorage.removeItem('avatarUrl');
                sessionStorage.removeItem('userRole'); // Assuming userRole is also stored

                // Redirect to login page
                window.location.href = '/login.html'; // Replace with your login page path
            });

        } catch (error) {
            console.error('初始化编辑器失败:', error);
            alert('初始化编辑器失败，请刷新页面重试');
        }
    });
</script>

</body>
</html> 